package com.example.yangxu0703.thundermapclient.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.example.yangxu0703.thundermapclient.R;
import com.example.yangxu0703.thundermapclient.util.ZxingUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.zxing.WriterException;
import com.thundersoft.mm.phone.ConnectionManager;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

public class UserCenterActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout connect_help, invite, feedback_option, about_us, send_apk, send_apk_action;
    private TextView wifi_status, bluetooth_status, user_name, AP_status;
    private SimpleDraweeView icon_user;
    private String blueName;
    private Bitmap bitmap;
    public WifiManager wifiManager;
    public static String SSID;
    public static String PASSWORD;
    private String TAG = "UserCenterActivity";
    private boolean ap_status = false;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (Build.VERSION.SDK_INT > 25) {
                        setWifiApEnabled_O();
                    } else {
                        boolean result = setWifiApEnabled_N(true);
                        Log.i(TAG, result + "-------------");
                    }
                    ConnectionManager.sendWifiInfo(SSID, PASSWORD);
                    break;
                case 2:

                    break;
                case 3:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_center);
        initView();
        BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        BluetoothAdapter adapter = manager.getAdapter();
        adapter.enable();
        blueName = adapter.getName();
        wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if (isWifiApEnabled()) {
            AP_status.setText("已开启");
            ap_status = true;
        } else {
            AP_status.setText("未开启");
            ap_status = false;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestWriteSettings() {
        if (!Settings.System.canWrite(this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 100);
        } else {
            handler.sendEmptyMessage(1);
        }
    }

    private void initView() {
        AP_status = findViewById(R.id.AP_status);
        wifi_status = findViewById(R.id.wifi_status);
        bluetooth_status = findViewById(R.id.bluetooth_status);
        icon_user = findViewById(R.id.icon_user);
        icon_user.setOnClickListener(this);
        user_name = findViewById(R.id.user_name);
        user_name.setOnClickListener(this);
        connect_help = findViewById(R.id.connect_help);
        connect_help.setOnClickListener(this);
        invite = findViewById(R.id.invite);
        invite.setOnClickListener(this);
        feedback_option = findViewById(R.id.feedback_option);
        feedback_option.setOnClickListener(this);
        send_apk = findViewById(R.id.send_apk);
        send_apk.setOnClickListener(this);
        send_apk_action = findViewById(R.id.send_apk_action);
        send_apk_action.setOnClickListener(this);
        about_us = findViewById(R.id.about_us);
        about_us.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.connect_help:
                try {
                    bitmap = ZxingUtil.createQRImage(blueName, 200, 200, BitmapDescriptorFactory.fromResource(R.drawable.app_icon).getBitmap());
                } catch (WriterException e) {
                    e.printStackTrace();
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                View view = LayoutInflater.from(this).inflate(R.layout.two_code_show, null, false);
                ImageView codeview = view.findViewById(R.id.code_view);
                codeview.setImageBitmap(bitmap);
                builder.setView(view);
                builder.show();
                break;
            case R.id.invite:
                startActivity(new Intent(UserCenterActivity.this, SelectContactActivity.class));
                break;
            case R.id.feedback_option:

                break;
            case R.id.send_apk:
                AlertDialog.Builder AP_dia = new AlertDialog.Builder(UserCenterActivity.this);
                View AP_view = LayoutInflater.from(UserCenterActivity.this).inflate(R.layout.dia_ap_operation, null, false);
                final TextView ap_title=AP_view.findViewById(R.id.ap_title);
                TextView ap_cancle = AP_view.findViewById(R.id.ap_cancle);
                TextView ap_conform = AP_view.findViewById(R.id.ap_conform);
                if (ap_status){
                    ap_title.setText("关闭热点");
                }else {
                    ap_title.setText("打开热点");
                }
                AP_dia.setView(AP_view);
                final Dialog dialog = AP_dia.create();
                ap_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                ap_conform.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.i(TAG,"setOnClickListener"+ap_status);
                        if (!ap_status) {
                            if (Build.VERSION.SDK_INT < 23) {
                                setWifiApEnabled_N(true);
                            } else {
                                requestWriteSettings();
                            }
                        }else {
                            closeWifiAp();
                            AP_status.setText("未开启");
                        }
                        dialog.dismiss();
                    }
                });

                dialog.show();

                break;
            case R.id.send_apk_action:
                 //if(ConnectionManager.mGlassesIp != null) {
                startActivity(new Intent(UserCenterActivity.this, SendApkActivity.class));
                /*} else {
                    Toast.makeText(this, "wifip2p未连接！", Toast.LENGTH_SHORT).show();
                }*/
                break;
            case R.id.about_us:

                break;
            case R.id.icon_user:
                 AlertDialog.Builder icon_choose = new AlertDialog.Builder(UserCenterActivity.this);
                 View choose=LayoutInflater.from(UserCenterActivity.this).inflate(R.layout.dia_icon_choose,null,false);
                 TextView camera =choose.findViewById(R.id.camera);
                 TextView forde=choose.findViewById(R.id.forde);
                 camera.setOnClickListener(new View.OnClickListener() {
                     @Override
                     public void onClick(View v) {
                         startActivityForResult(new Intent(),102);
                     }
                 });
                 forde.setOnClickListener(new View.OnClickListener() {
                     @Override
                     public void onClick(View v) {
                         startActivityForResult(new Intent(),103);
                     }
                 });
                //弹出dialog
                break;
            case R.id.user_name:
                 AlertDialog.Builder notify_uname = new AlertDialog.Builder(UserCenterActivity.this);
                //弹出dialog
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            handler.sendEmptyMessage(1);
        }
    }

    public boolean setWifiApEnabled_N(boolean enabled) {
        Method getwifiApConfig;
        WifiConfiguration mWifconfig = null;
        if (enabled) {
            wifiManager.setWifiEnabled(false);
        }
        try {
            getwifiApConfig = wifiManager.getClass().getMethod("getWifiApConfiguration");
            getwifiApConfig.setAccessible(true);
            mWifconfig = (WifiConfiguration) getwifiApConfig.invoke(wifiManager);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        Field[] fields = mWifconfig.getClass().getDeclaredFields();
        if (fields != null) {
            for (Field field : fields) {
                Log.i(TAG, field.getName());
                if (field.getName().equals("SSID")) {
                    try {
                        SSID = field.get(mWifconfig).toString();
                        Log.i(TAG, "---" + SSID);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                } else if (field.getName().equals("preSharedKey")) {
                    try {
                        PASSWORD = field.get(mWifconfig).toString();
                        Log.i(TAG, "---" + PASSWORD);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        startWifiAp_N(SSID, PASSWORD, true);
        return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void setWifiApEnabled_O() {
        WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {

            @Override
            public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
                super.onStarted(reservation);
                SSID = reservation.getWifiConfiguration().SSID;
                PASSWORD = reservation.getWifiConfiguration().preSharedKey;
            }

            @Override
            public void onStopped() {
                super.onStopped();
                Log.d(TAG, "onStopped: ");
            }

            @Override
            public void onFailed(int reason) {
                super.onFailed(reason);
                Log.d(TAG, "onFailed: ");
            }
        }, new Handler());

    }

    public void startWifiAp_N(String mSSID, String mPasswd, boolean isOpen) {
        Method method1 = null;
        try {
            method1 = wifiManager.getClass().getDeclaredMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            WifiConfiguration netConfig = new WifiConfiguration();
            netConfig.SSID = mSSID;
            netConfig.preSharedKey = mPasswd;
            netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            if (isOpen) {
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            } else {
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            }
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            method1.invoke(wifiManager, netConfig, true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public boolean isWifiApEnabled() {
        try {
            Method method = wifiManager.getClass().getMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (boolean) method.invoke(wifiManager);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void closeWifiAp() {
        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (isWifiApEnabled()) {
            try {
                Method method = wifiManager.getClass().getMethod("getWifiApConfiguration");
                method.setAccessible(true);
                WifiConfiguration config = (WifiConfiguration) method.invoke(wifiManager);
                Method method2 = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
                method2.invoke(wifiManager, config, false);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public ArrayList<String> getConnectedIP() {
        ArrayList<String> connectedIp = new ArrayList<String>();
        try {
            BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));
            String line;
            while ((line = br.readLine()) != null) {
                String[] splitted = line.split(" +");
                if (splitted != null && splitted.length >= 4) {
                    String ip = splitted[0];
                    if (!ip.equalsIgnoreCase("ip")) {
                        connectedIp.add(ip);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return connectedIp;
    }
}
